package org.gtugs.raffler.pojo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

public class Raffle {
	private String title;
	private List<Prize> prizes;
	private List<Participant> participants;
	private HashMap<Prize, Participant> winnerList;
	
	private long drawingTimestamp;
	/**
	 * @param title Title of the raffle
	 * @param prizes List of prizes
	 * @param drawingTimestamp optional timestamp of when the drawing will be held
	 */
	public Raffle(String title, long drawingTimestamp) {
		super();
		this.title = title;
		this.drawingTimestamp = drawingTimestamp;
		participants = new ArrayList<Participant>();
		prizes = new ArrayList<Prize>();
		winnerList = null; // initial set to null until drawing has been done
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public List<Prize> getPrizes() {
		// Sort by weight
		Collections.sort(prizes, COMPARATOR);
		return prizes;
	}
	
	public void addPrize(Prize prize) {
		for(int i = 0; i <= prize.getCount(); i++) {
			this.prizes.add(prize);
		}
		
	}
	
	
	
	public List<Participant> getParticipants() {
		return participants;
	}
	
	public boolean addParticipant(Participant participant) {
		if(participants.contains(participant) || getWinnerList() != null)
			return false;
		return participants.add(participant);
		
	}
	public HashMap<Prize, Participant> getWinnerList() {
		if(winnerList != null) {
			if(winnerList.isEmpty())
				return null;
		}
		return winnerList;
	}
	public long getDrawingTimestamp() {
		return drawingTimestamp;
	}
	public void setDrawingTimestamp(long drawingTimestamp) {
		this.drawingTimestamp = drawingTimestamp;
	}
	
	public HashMap<Prize, Participant> doDrawing() {
		//TODO implement drawing
		winnerList = new HashMap<Prize, Participant>();
		

		Random rand = new Random(new Date().getTime());
		int min = 0, max = participants.size()-1;

		for (Prize prize : prizes) {
			        // choose a winner for the prize
					// nextInt is normally exclusive of the top value,
					// so add 1 to make it inclusive
					int randomNum = rand.nextInt(max - min + 1) + min;
					try {
						winnerList.put(prize, participants.get(randomNum));
					} catch (Exception e) {
						randomNum = rand.nextInt(max - min + 1) + min;
						winnerList.put(prize, participants.get(randomNum));
					}
			    }
		
		return winnerList;
	}
	
	private static Comparator<Prize> COMPARATOR = new Comparator<Prize>()
			    {
			    // This is where the sorting happens.
			        public int compare(Prize o1, Prize o2)
			        {
			            return o1.getWeight() - o2.getWeight();
			        }
			    };

	

}
